import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from "@/store"
import { GetUserRoutersApi } from "@/request/api"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'mainlayout',
    component: () => import("../views/layout/MainLayout.vue"),
    redirect: "/home",
    // children:[
    //   {
    //     path:"/home",
    //     component: () => import(/* webpackChunkName: "home" */ '../views/HomeView.vue')
    //   },
    //   {
    //     path:"/customer/customer",
    //     component: () => import(/* webpackChunkName: "customer" */ '../views/customer/Customer.vue')
    //   },
    //   {
    //     path:"/customer/visit",
    //     component: () => import(/* webpackChunkName: "visit" */ '../views/customer/Visit.vue')
    //   },
    //   {
    //     path:"/flow/definition",
    //     component: () => import(/* webpackChunkName: "definition" */ '../views/flow/Definition.vue')
    //   }
    // ]
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/Login/Login.vue')
  },
  {
    path: '*',
    component: () => import(/* webpackChunkName: "404" */ '../views/404.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  //只有next()是放行，加了路径就是跳转
  const token = localStorage.getItem('edb-authorization-token')
  //访问登录页面，但是token存在，跳转到首页
  if (to.path == "/login" && token) {
    next("/")
    return
  }
  // 访问不是登录页，但是没有token，跳转登录页
  if (to.path !== "/login" && !token) {
    next("/login")
    return
  }
  if (token && store.state.userMenuData.menuData.length == 0) {
    // 获取用户的菜单数据
    let GetUserRoutersApiRes = await GetUserRoutersApi();
    console.log("GetUserRoutersApiRes为：", GetUserRoutersApiRes);
    if (!GetUserRoutersApiRes) return;
    let newMeauData = [{ title: "首页", path: "/", icon: "dashboard" }]
    let ret = GetUserRoutersApiRes.data.data.map(item => {
      if (item.children) {
        return {
          title: item.meta.title,
          path: item.path,
          icon: item.meta.icon,
          children: item.children.map(items => {
            return {
              title: items.meta.title,
              path: item.path + "/" + items.path,
              icon: items.meta.icon
            }
          })
        }
      } else {
        return {
          title: item.meta.title,
          path: item.path,
        }
      }

    });
    newMeauData = [...newMeauData, ...ret]
    store.commit("userMenuData/changeMenuData", newMeauData)
    // console.log(newMeauData);
    // 以上生成表单数据
    // 一下生成用户路由数据
    let newChildrenRoutes = [{
      path: "/home",
      meta:{titles:["首页"]},
      component: () => import('../views/HomeView.vue')
    }];
    GetUserRoutersApiRes.data.data.forEach(item => {
      let ret = item.children.map(sitem => {
        return {
          path: item.path + '/' + sitem.path,
         meta:{titles:[item.meta.title,sitem.meta.title]},
          component: () => import(`../views${item.path}/${sitem.name}.vue`)
        }
      })
      newChildrenRoutes = [...newChildrenRoutes, ...ret]
    })
    console.log(newChildrenRoutes);
    // 再利用router.addRoute(父路由名称，单个子路由对象);  把刚才的子路由添加到mainlayout路由里面去。
    newChildrenRoutes.forEach(item => {
      router.addRoute('mainlayout', item)
    })
    // console.log(to.path);
    //如果直接next()，路由还没有完整，还是空的，他不确定路由里面有没有这个路径
    //加了to.path后，会重新走一遍路由守卫，此时路由添加完毕，可以检查出用户能不能访问这个路径
        next(to.path)
    return
  }
  next()
})
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => {})
};
export default router
